package com.zhanghe.security.provider;

import com.zhanghe.security.authenticationtoken.GithubAuthenticationToken;
import com.zhanghe.security.excepiton.LoginException;
import com.zhanghe.security.service.SimpleUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

public class NormalProvider implements AuthenticationProvider {

    protected static final Logger logger = LoggerFactory.getLogger(NormalProvider.class);

    @Autowired
    private SimpleUserDetailsService simpleUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken)authentication;
        UserDetails userDetails = simpleUserDetailsService.loadUserByUsername(auth.getPrincipal().toString());
        if(auth.getCredentials()==null||!auth.getCredentials().equals(userDetails.getPassword())){
            throw new LoginException("账号密码错误");
        }
        Authentication res = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),"",userDetails.getAuthorities());
        return res;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }
}
